/** 
 *    
 *  Copyright (C) 2008 Marco Speranza <marco.speranza79@gmail.com>
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */
package org.commons.database.jconnectionpool;

import java.sql.SQLException;

import javax.sql.ConnectionEvent;
import javax.sql.ConnectionEventListener;
import javax.sql.PooledConnection;

/**
 * Classe wrapper per la poolled connessione
 * 
 * @author <a href="mailto:msperanza@users.sourceforge.net">Marco Speranza</a>
 * @version $Id: DataBaseManager.java,v 1.1 2006/08/10 09:48:09 msperanza Exp $
 */
public class WrapPooledConnection  implements ConnectionEventListener { 

	private final PoolConnectionManager poolConnectionManager;
	private final PooledConnection connPool;
	private boolean isAvaiable;

	/**
	 * Costruttore
	 * 
	 * @param connPool
	 *            la connection pool da wrappare *
	 */
	public WrapPooledConnection(PooledConnection connPool, PoolConnectionManager poolConnectionManager) {
		super();
		this.connPool = connPool;
		this.poolConnectionManager = poolConnectionManager;
		setAvaiable(true);
	}

	/**
	 * Recupera la conneccione pool wrappata
	 * 
	 * @return the connPool <code>PooledConnection</code>
	 */
	public synchronized PooledConnection getPooledConnection() {
		return connPool;
	}

	/**
	 * Testa se la connessione � disponibile
	 * 
	 * @return torna true nel caso in cui la connessione e' disponibile, false
	 *         altrimenti
	 */
	public synchronized boolean isAvaiable() {
		return isAvaiable;
	}

	/**
	 * Setta lo stato della connessione
	 * 
	 * @param isAvaiable
	 *            true per settare la connessioen disponibile.
	 */
	public synchronized void setAvaiable(boolean isAvaiable) {
		this.isAvaiable = isAvaiable;
	}

	
	
	
	public void connectionClosed(ConnectionEvent event) {
		setAvaiable(true);
		try {
			poolConnectionManager.fairedConnectionAvaiable(this);
		} catch (SQLException e) {
			poolConnectionManager.fairedConnectionErrorOccurred(this, new ConnectionEvent(connPool,e));
		}
	}

	public void connectionErrorOccurred(ConnectionEvent event) {		
		poolConnectionManager.fairedConnectionErrorOccurred(this, event);
	}

}
